<?php
function mobile_service_farmer_list($parameters)
{
    global $user;
    $query = db_select('addr', 'A');
    $query->join('farmer', 'F', 'A.addr_id=F.addr_id');
    $query->leftJoin('distributor', 'D', 'D.distributor_id=F.distributor_id');
    $query->join('users','U','U.uid=F.farmer_id');

    //地址级别查询
    if (!empty($parameters['village'])) {//乡镇级
        $query->condition('A.village_id', $parameters['village'], '=');
    } else if (!empty($parameters['county'])) {//乡镇级
        $query->condition('A.county_id', $parameters['county'], '=');
    } else if (!empty($parameters['town'])) {//乡镇级
        $query->condition('A.town_id', $parameters['town'], '=');
    } elseif (!empty($parameters['county'])) {//县级
        $query->condition('A.county_id', $parameters['county'], '=');
    } elseif (!empty($parameters['city'])) {//市级
        $query->condition('A.city_id', $parameters['city'], '=');
    } elseif (!empty($parameters['province'])) {//省级
        $query->condition('A.province_id', $parameters['province'], '=');
    }
    if(!user_access('view all farmer') && user_access('view own farmer')){
        $query->condition('F.author_uid',$user->uid, '=');
    }
    //模糊条件筛选
    if (!empty($parameters['farmer_name'])) {//农户名字
        $query->condition('F.farmer_name', '%' . db_like($parameters['farmer_name']) . '%', 'LIKE');
    }
    if (!empty($parameters['cell'])) {//模糊电话号码查询条件
        $query->condition('F.cell', db_like($parameters['cell']) . '%', 'LIKE');
    }
    $query->fields('F');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.town_id');
    $query->leftJoin('addr', 'A5', 'A.village_id=A5.village_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A5', 'name', 'village');
    $query->addField('D', 'distributor_name');
    $query->addField('U', 'name');
    $query->orderBy('F.farmer_id', 'DESC');
    if (!empty($parameters['cursor']) && !empty($parameters['comparator'])) { //游标翻页
        $query->condition('F.farmer_id', $parameters['cursor'], $parameters['comparator']);
    }
    $query->range(0,10);

    $results = $query->execute();
    $results_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $results_list[] = $result;
        }
    }
    return  ["data"=>$results_list];
}
function farmer_add_validate( &$parameters) {
    $validata_error = '';

    if(isset($parameters['farmer_id']) ) {
        if(empty($parameters['farmer_id'])){
            if(isset($parameters['address_fuzzy'])&&!empty($parameters['address_fuzzy'])) {
                $addr_object = table_load("addr", "full_name", $parameters['address_fuzzy']);
                if (empty($addr_object)) {
                    $validata_error .= '请根据提示输入正确（完整）的地址信息';
                }
            }
            if(empty($parameters['farmer_name'])){
                $validata_error .= '必填 农户姓名.';
            }
            if(empty($parameters['cell'])){
                $validata_error .= '必填 手机号.';
            }else{
                $return_value = pregPN($parameters['cell']);
                if(empty($return_value)){
                    $validata_error .= '请填写正确的 手机号.';
                    return $validata_error;
                }
                if ($error = user_validate_name($parameters['cell'])) {
                    $validata_error .=$error;
                }elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('name', db_like($parameters['cell']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
                    $validata_error .= '手机号：'.$parameters['cell'].' 已注册.' ;
                }
            }

//            if (isset($parameters['account'])&&!empty($parameters['account'])) {
//                if ($error = user_validate_name($parameters['account'])) {
//                    $validata_error = $error;
//                }
//                elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('name', db_like($parameters['account']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
//                    $validata_error .= '用户名 '.$parameters['account'] .'已存在.' ;
//                }
//            }

//            if (empty($parameters['account'])) {
//                $record = db_select('users', 'u')
//                    ->condition('u.name', $parameters['cell'])
//                    ->fields('u')
//                    ->execute()->fetchAssoc();
//                if (!empty($record)) {
//                    $validata_error .= '利用该手机号作为登录名，该手机号已存在！';
//                }
//            }
        }


    }else{
        $validata_error .= '参数有误.';
    }
    return $validata_error;
}

function mobile_service_farmer_add($parameters)
{
    $validate_result = farmer_add_validate($parameters);
    if(!empty($validate_result)){
        $result_option = (object)["option" => 0,"error"=>$validate_result];
        return $result_option;
    }
    global $user;
    $module_name = "farmer";
    $id = $parameters['farmer_id'];


    $address = '';
    if(isset($parameters['address_fuzzy'])&&!empty($parameters['address_fuzzy'])){
        $addr_object = addr_load_by_full_name($parameters['address_fuzzy']);
        $address = $addr_object->addr_id;
    }else{
        $address = isset($parameters['addr_id']) && !empty($parameters['addr_id']) ?$parameters['addr_id'] :null;
    }

    $transaction = db_transaction();
    try {
        $role_result = user_role_load_by_name('农户');
        if (empty($id)) { //add new farmer
            if (!user_access('add ' . $module_name)) {
                return ['option' => 0, 'errorNum' => 3,'error' => '无权限.'];
            }
            $new_user = array(
                'name' => $parameters['cell'],
                'pass' =>  '123456',
                'mail' => isset($parameters['email'])?$parameters['email']:null,
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' => isset($parameters['email'])?$parameters['email']:null,
                'roles' => array(
                    $role_result->rid =>  '农户',
                ),
            );
            $account = user_save('', $new_user);
            $nid = db_insert('farmer')// Table name no longer needs {}
            ->fields(array(
                'farmer_id' => $account->uid,
                'farmer_name' => isset($parameters['farmer_name'])&&!empty($parameters['farmer_name'])?$parameters['farmer_name']:null,

                'addr_id' => $address,

                'cell' => isset($parameters['cell'])&&!empty($parameters['cell'])?$parameters['cell']:null,
                'gender' => isset($parameters['gender'])&&!empty($parameters['gender'])?$parameters['gender']:null,
                'email' => isset($parameters['email'])&&!empty($parameters['email'])?$parameters['email']:null,
                'farm_area' => isset($parameters['farm_area'])&&!empty($parameters['farm_area'])? $parameters['farm_area'] : '0',
                'soil_type' => isset($parameters['soil_type']) &&!empty($parameters['soil_type'])?$parameters['soil_type']:null,
                'soil_fertility' => isset($parameters['soil_fertility'])&&!empty($parameters['soil_fertility'])?$parameters['soil_fertility']:null,
                'comments' => isset($parameters['comments'])&&!empty($parameters['comments'])?$parameters['comments']:null,
                'status'=>'农户',
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            $result_option = (object)["option" => 1];
            return $result_option;
        } else {
            if (!mobile_user_edit_access($module_name, $module_name . '_id', $id, 'edit own ' . $module_name, 'edit all ' . $module_name)) {
                return ['option' => 0, 'errorNum' => 3];
            }
            $new_user = array(
                'mail' => isset($parameters['email'])?$parameters['email']:null,
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' =>isset($parameters['email'])?$parameters['email']:null,
                'roles' => array(
                    $role_result->rid =>  '农户',
                ),
            );
            $account  = user_load($parameters['farmer_id']);
            user_save($account, $new_user);

            $nid = db_update('farmer')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'farmer_name' => isset($parameters['farmer_name'])&&!empty($parameters['farmer_name'])?$parameters['farmer_name']:null,
                'gender' => isset($parameters['gender'])&&!empty($parameters['gender'])?$parameters['gender']:null,
                'addr_id' => $address,
                'addr_details' => isset($parameters['addr_details'])&&!empty($parameters['addr_details'])?$parameters['addr_details']:null,
                'distributor_id' => isset($parameters['distributor_id'])&&!empty($parameters['distributor_id'])?$parameters['distributor_id']:null,
                'type' => isset($parameters['type'])&&!empty($parameters['type'])?$parameters['type']:null,
                'phone' => isset($parameters['phone'])&&!empty($parameters['phone'])?$parameters['phone']:null,
                'cell' => isset($parameters['cell'])&&!empty($parameters['cell'])?$parameters['cell']:null,
                'email' => isset($parameters['email'])&&!empty($parameters['email'])?$parameters['email']:null,
                'farm_area' => isset($parameters['farm_area'])&&!empty($parameters['farm_area'])? $parameters['farm_area'] : '0',
                'soil_type' => isset($parameters['soil_type']) &&!empty($parameters['soil_type'])?$parameters['soil_type']:null,
                'soil_fertility' => isset($parameters['soil_fertility'])&&!empty($parameters['soil_fertility'])?$parameters['soil_fertility']:null,
                'comments' => isset($parameters['comments'])&&!empty($parameters['comments'])?$parameters['comments']:null,
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->condition('farmer_id', $id, '=')
                ->execute();
            $result_option = (object)["option" => 1];
            return $result_option;
        }
    } catch (Exception $e) {
        $transaction->rollback();
        $result_option = (object)["option" => 0,"error"=>$e->getMessage()];
        return $result_option;
    }
}
function farmer_load($id) {
    $result = db_select('farmer', 'P')
        -> fields('P')
        -> condition('P.farmer_id',$id, '=')
        -> execute()
        -> fetchObject();
    return $result;
}
